<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     Pagizer
 * @subpackage  backoffice
 */

/**
 * Display login form to the backoffice
 * Will check if there is a user in db, if not display form to create a new one
 * Will already check if application is initialized, if not redirect to install script
 */
class m_backoffice_actions_loginAction extends f_core_Action
{
	public function execute()
	{
		$values = $this->getRequest()->getParameterValues('loginForm');
		$currentHref = $this->getRequest()->getParameterValues('href');
		$bool = !empty($currentHref) ? true : false;
		$errors = array();

		if(!is_null($values))
		{
			$errors = $this->checkLoginForm($values);

            // user exists
			if(count($errors) == 0)
			{
				$documentProvider = f_document_Provider::getInstance();

                $key = m_backoffice_services_BackOfficeService::getKey();
				$user = $documentProvider->loadDocuments('modules_users/user')->whereIsEqual('login', $values['name'])->whereIsEqual('password', md5($values['password'].$key))->retrieveFirstDocument();
				
				$rights = m_rights_services_RightsService::getInstance()->getUserRights($user);
				$this->getUserContext()->removeRights()->setUser($user);
				
                $backOfficeContext = array();

                $this->setDisplayLang($user->getBackLang());
				
				foreach($rights as $right)
				{
					$this->getUserContext()->addRight($right);
				}

				if(!$bool)
				{
                    $cookie = f_core_Cookie::getInstance()->setName($user->getLogin())->getCookie();

                    $url = URL_RELATIVE.'/bo';
                    if(isset($cookie['lastUrl']))
                    {
                        $lastUrl = URL_RELATIVE.'/bo/#'.$cookie['lastUrl'];
                        $routing = f_core_Routing::getInstance()->setRequestURL($cookie['lastUrl']);
                        $array = array('website','medias','users','system');

                        if(in_array($routing->getModule(), $array))
                        {
                            if(in_array('backoffice_access'.ucfirst($routing->getModule()),$rights))
                            {
                                $url = $lastUrl;
                            }
                        }
                    }

                    $this->getController()->redirect('Location:'.$url);
					return false;
				}
				else
				{
					$href['status'] = 'success';
				}
			}
		}
        else
        {
            $lang = f_core_Context::getInstance()->getBrowserLanguage();
            $this->setDisplayLang($lang);
        }
		
		$href["url"] = $currentHref[0];
		$this->addToModel("href", $href);
		$this->addToModel("errors", $errors);
		
		if($bool)
		{
			$this->setView("nyroSuccess");			
		}
		else
		{
			$this->setView("success");
		}
	}	
	
	public function validate()
	{
        return $this->checkForInstall();
	}
	
	public function errorHandler()
	{
        if(!$this->checkForInstall())
        {
            return $this->launchAction("install", "InstallPagizer");
        }			
	}

    private function checkForInstall()
    {
        if(!f_database_Provider::checkConnect()) return false;
        if(!f_database_Provider::getInstance()->tableExists('m_users__group')) return false;
        if(!m_users_services_UserService::getInstance()->hasAdminUser()) return false;
		if(f_document_Provider::getInstance()->loadDocuments("modules_website/website")->count('*') > 0) return true;
    }

	/**
	 * Check login form
	 * 
	 * @param $values
	 * @return array
	 */
	private function checkLoginForm($values)
	{
		$errors = array();

		$documentProvider = f_document_Provider::getInstance();

		$key = m_backoffice_services_BackOfficeService::getKey();
		$checkUser = $documentProvider->loadDocuments("modules_users/user")
                        ->whereIsEqual("login", $values['name'])
                        ->whereIsEqual("password", md5($values['password'].$key))
                        ->count();

		if($checkUser == 0)
		{
			$errors["errors"] = $this->getLocale('backoffice.errors.loginFailed', null, null, 'Autentication failed');
		}
		
		return $errors;
	}	
}